package com.shenmazong.serveredugateway.config;

import com.shenmazong.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2021/9/22 20:28
 */

@Configuration
public class GatewayFilter implements GlobalFilter, Ordered {

    /**
     * 全局过滤
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取Request、Response对象

        /*ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 解决中文乱码问题
        HttpHeaders headers = response.getHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 打印输出URI
        String requestUrl = exchange.getRequest().getURI().getRawPath();
        System.out.println(requestUrl);
        System.out.println(request.getURI());

        if(requestUrl.equals("/user/admin/login") || requestUrl.equals("/user/student/login") || requestUrl.equals("/user/staff/login")){
            System.out.println("用户来登陆了  直接放过");
            return chain.filter(exchange);
        }
        String accessToken = request.getHeaders().getFirst("accessToken");
        // 判断token 是否为空
        if (StringUtils.isEmpty(accessToken)){
            String msg = "{'code':-1,'message':'您未登录，请先登录'}";
            DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        //检验token
        boolean b = JwtUtils.verifyToken(accessToken);

        if(!b){
            String msg = "{'code':-2,'message':'token不合法'}";
            DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }*/



        return chain.filter(exchange);
    }

    /**
     * 排序，越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
